#coding=utf-8
from datetime import datetime
import time
import os
import json
from apscheduler.schedulers.background import BackgroundScheduler
from tool.redis_tool import initRedis
from tool.tool import get, digital_to_chinese, to_chinese, ting
redis = initRedis()

def tick():
    print('Tick! The time is: %s' % datetime.now())
    result = redis.get("warn:now")
    result = json.loads(result)
    fault = 0
    standard = 0
    offline = 0
    for r in result["data"]:
        print(r)
        state = r["state"]
        if state == "1" or state == "4":
            offline += 1
        if state == "2":
            standard += 1
        if state == "3":
            fault += 1
    standard = digital_to_chinese(standard)
    fault = digital_to_chinese(fault)
    offline = digital_to_chinese(offline)
    str = f"当前有{standard}台设备超标 {fault}台设备故障 {offline}台设备离线"
    print(str)
    get(f"http://127.0.0.1:6006/synthesize?text={str}","报警")

def tick2():
    print('Tick! The time is: %s' % datetime.now())
    start = time.time()
    result = redis.get("warn:now")
    result = json.loads(result)
    fault = 0
    fault_arr = []
    standard = 0
    standard_arr = []
    offline = 0
    offline_arr = []
    for r in result["data"]:
        state = r["state"]
        if r["equip_type"] == "1":
            continue
        if state == "1" or state == "4":
            offline += 1
            offline_arr.append(r["name"])
        if state == "2":
            standard += 1
            standard_arr.append(r["name"])
        if state == "3":
            fault += 1
            fault_arr.append(r["name"])
    if standard > 0:
        names = to_chinese(",".join(standard_arr))
        standard = digital_to_chinese(standard)
        str = f"当前有{standard}台超标,{names}"
        get(f"http://127.0.0.1:6006/synthesize?text={str}", "报警")
    if fault > 0:
        names = to_chinese(",".join(fault_arr))
        fault = digital_to_chinese(fault)
        str = f"当前有{fault}台故障,{names}"
        get(f"http://127.0.0.1:6006/synthesize?text={str}", "报警")
    if offline > 0:
        names = to_chinese(",".join(offline_arr))
        offline = digital_to_chinese(offline)
        str = f"当前有{offline}台离线,{names}"
        get(f"http://127.0.0.1:6006/synthesize?text={str}", "报警")
    end = time.time()
    print("执行时间: %s seconds" % (end - start))

if __name__ == '__main__':
    tick2()
    # scheduler = BackgroundScheduler()
    # # 间隔3秒钟执行一次
    # scheduler.add_job(tick2, 'interval', seconds=180)
    # # 这里的调度任务是独立的一个线程
    # scheduler.start()
    # try:
    #     # 其他任务是独立的线程执行
    #     while True:
    #         time.sleep(2)
    # except (KeyboardInterrupt, SystemExit):
    #     scheduler.shutdown()
    #     print('Exit The Job!')